--
-- Created by IntelliJ IDEA.
-- User: aoogin
-- Date: 14-7-11
-- Time: 上午10:57
-- To change this template use File | Settings | File Templates.
--

local ManagerNotification = {};

function ManagerNotification:registerObserver(eventName, target, eventHandler, times)  --注册了事件会加入事件池
    if times == nil then
        times = -1;
    end

    if ManagerNotification.eventList == nil then
        ManagerNotification.eventList = {};
    end

    if ManagerNotification.eventList[eventName] == nil then
        ManagerNotification.eventList[eventName] = {};
    end

    if ManagerNotification.eventList[eventName][target] == nil then
        ManagerNotification.eventList[eventName][target] = {};
    end
    table.insert(ManagerNotification.eventList[eventName][target], {call=eventHandler, times=times});
end

function ManagerNotification:unregisterObserver(eventName, target)
    if ManagerNotification.eventList[eventName] and ManagerNotification.eventList[eventName][target] then
        ManagerNotification.eventList[eventName][target] = nil;
    end
end

function ManagerNotification:post(eventName, ...)

    if ManagerNotification.eventList == nil then
        ManagerNotification.eventList = {};
    end

    if ManagerNotification.eventList[eventName] then  --事件池里没参数事件时 post什么都不做
        for k, v in pairs(ManagerNotification.eventList[eventName]) do  --遍历同名事件
            for k1, v1 in pairs(v) do  --遍历同名同对象事件
                if v1.times ~= -1 then   --time 为-1 时永远监听  需要手动删除  为1时监听一次
                    v1.times = v1.times - 1;
                end
                v1.call(...);
                if v1.times == 0 then -- times为0 时事件移除
                    v[k1] = nil;
                end

                if table.nums(v) == 0 then
                    ManagerNotification.eventList[eventName][k] = nil;
                end
            end
            if table.nums(ManagerNotification.eventList[eventName]) == 0 then
                ManagerNotification.eventList[eventName] = nil;
            end
        end
    end
end

return ManagerNotification